import java.util.*;
import java.util.function.BiConsumer;

/**
 * @author Macrydy
 * @date 2022/5/10
 *
 * Map：
 * 双列集合,一个键对应一个值、键不可以重复,值可以重复
 */
public class MapDemo {
    public static void main(String[] args) {

        //hashmap存取无序
        Map<String, Integer> map = new HashMap<>();
        map.put("xiaoming", 18);
        map.put("xiaobai", 28);
        map.put("xiaohong", 19);

        //三种遍历方式
        //1.获取所有键的集合keySet()
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            System.out.println("键："+s+",值："+map.get(s));
        }
        //2.获取所有键值对对象的集合entrySet()
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            System.out.println("键："+entry.getKey()+",值："+entry.getValue());
        }
        //3.foreach
        map.forEach(new BiConsumer<String, Integer>() {
            @Override
            public void accept(String s, Integer integer) {
                System.out.println("键："+s+",值："+integer);
            }
        });


        System.out.println("----------TreeMap-----------");
        Map<Student, String> treemap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int result = o2.getAge() - o1.getAge();
                return result=result==0?o1.getName().compareTo(o2.getName()):result;
            }
        });
        treemap.put(new Student("xiaoming", 18), "洛阳");
        treemap.put(new Student("xiaoming", 23), "广东");
        treemap.put(new Student("xiaobai", 25), "上海");

        System.out.println(treemap);

        //给定一个字符串，要求统计字符串中每个元素出现的次数
        //aababcabcdabcde
        System.out.println("案例：要求统计字符串'aababcabcdabcde'中每个元素出现的次数");

        String str = "aababcabcdabcde";

        Map<Character, Integer> tree = new TreeMap<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (tree.containsKey(c)) {
                Integer count = tree.get(c);
                count++;
                tree.put(c, count);
            }else {
                tree.put(c, 1);
            }
        }

        System.out.println(tree);

    }

}
